import json
# 将view需要的共同模块进行封装到一个文件
from utils.common_import import *
from .model import Management_User
from utils.ext import inner_db, db_add_record, db_query_record, db_delete_record, db_update_record, db_transaction
from .model import UserAddSchema, UserDeleteSchema, UserUpdateSchema, TokenManageAddSchema

"""
对装饰器顺序有要求
permission_auth_admin在内
jwt_required 在外
执行时先执行jwt_required 校验密码信息
permission_auth_admin 会根据jwt_required获取用户信息
"""


class UserManage(Resource):
    # @jwt_required()
    @exception_response()
    def get(self):
        users_list = db_query_record(Management_User)

        return make_success_response(users_list)

    # 新增
    @request_arg_check(UserAddSchema(), many=False)
    # @jwt_required()
    @permission_auth("admin")
    @exception_response()
    @db_transaction(inner_db.session)
    def post(self):
        user_info = current_schema_instance
        db_add_record(session=inner_db.session,
                      table_schema=Management_User,
                      filter_info=dict(email=user_info["email"]),
                      add_info=user_info)

        return make_no_data_response(status=200, code=0, message="success")

    # 修改
    @request_arg_check(UserUpdateSchema())
    # @jwt_required()
    @permission_auth("admin")
    @exception_response()
    @db_transaction(inner_db.session)
    def put(self):
        # verify data
        user_info = current_schema_instance
        record = Management_User.query.filter_by(email=user_info["email"]).first()
        if not record:
            raise Exception("record not find by email:{}".format(user_info["email"]))

        for key in user_info.keys():
            if key == "password":
                record.password = user_info[key]
            elif hasattr(record, key):
                setattr(record, key, user_info[key])

        return make_no_data_response(status=200, code=0, message="success")

    # 删除
    @request_arg_check(UserDeleteSchema())
    # @jwt_required()
    @permission_auth("admin")
    @exception_response()
    @db_transaction(inner_db.session)
    def delete(self):
        user_info = current_schema_instance
        db_delete_record(
              session=inner_db.session,
              table_schema=Management_User,
              filter_info=dict(email=user_info["email"]))

        return make_no_data_response(status=200, code=0, message="success")


class TokenManage(Resource):
    # 退出登录
    # @jwt_required()
    @exception_response()
    def delete(self):
        return make_no_data_response(status=200, code=0, message="logout successfully")

    # 登陆
    @request_arg_check(TokenManageAddSchema(), many=False)
    @exception_response()
    def post(self):
        with current_app.test_client() as internal_client:
            username = current_schema_instance["username"]
            password = current_schema_instance["password"]
            # 为了统一格式，内部转发到/auth路径进行认证
            resp = internal_client.post('/auth',
                                        headers={'Content-Type': 'application/json'},
                                        data=json.dumps({"username": username, "password": password}))

            data = json.loads(resp.data.decode('utf8'))
            if 'error' in data:
                response = jsonify(data)
                response.status_code = data['status_code']
                return response

            return make_success_response(dict(token=data['data']['token'],
                                              account=data['data']['account'],
                                              role=data['data']['role']))


class UserInfo(Resource):
    @exception_response()
    def get(self):
        return make_success_response(dict(role=current_identity.role, account=current_identity.account))